import React, { Component } from 'react';
import {
  View, Text, StyleSheet, TouchableOpacity, Image, TextInput, ScrollView,
  PixelRatio, Alert, Keyboard, Modal
} from 'react-native';
import ImagePicker from 'react-native-image-picker';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import ValidateDataUtil from '../../../utils/ValidateDataUtil';
import MethodUtil from '../../../utils/MethodUtil';
import StorageHelper from '../../../utils/storageHelper';
import Upload from '../../../utils/Upload';
import { STORAGE_CONSTANT } from '../../../config/storage';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import ModalPicDelComponent from '../../../component/ModalPicDelComponent';
import ProductSelectAll from '../../product/modals/ProductSelectAll';
import { enterpriseStyles } from '../_common/enterpriseStyle';
import { OptionCheck } from '../_components/Component';
import { Common } from '../../../component/common/Common';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import ModalAreaComponent from '../../../component/ModalAreaComponent.js';
import DatePicker from 'react-native-datepicker'
import Dictionary from '../../../utils/dictionary';

const scale = GLOBAL.SCALE;

const arrowLeft = require('../../../imgs/arrow-left.png');
const uploadPic = require('../../../imgs/store/upload.png');

const modalPicDelCfg = {
  visible: false,
  uri: null,
  delPress: () => { },
  picPress: () => { },
  fileId: '',
}
const fileIdObj = {};

let requireQualification = {};
let companyTypeListData = [];
let companyCapitalListData = [];
const addressObj = {
}
let bankLabel = '';
let responseDataParams = {};

export class EnterpriseCreateBaseInfo extends Component {

  static navigationOptions = ({ navigation }) => {
    const params = navigation.state.params || {};
    const { addressCodeParam, setEditInfo, setReference, users, responseData,
      checkCountryInfo, setCountryParams } = params;
    responseDataParams = responseData;
    if (responseDataParams) {
      responseDataParams.step = 1;
    }

    if (checkCountryInfo) {
      setCountryParams(checkCountryInfo);
    }

    if (users && setReference) {
      setReference(users);
    }

    if (responseData) {
      setEditInfo(
        responseData
      );
    }

    if (addressCodeParam) {
      addressObj = addressCodeParam;

      if (params.setAddress) {
        params.setAddress(addressObj);
      }

    }
    return {
      header: null,
    };
  };

  requesting;
  constructor(props) {
    super(props);
    this.state = {
      companyNatureText: '请选择',
      companyTypeText: '请选择',
      corpTypeText: '请选择',
      productText: '请选择',
      referenceStr: '',
      creditFileSource: null,
      resultModalVisible: false,
      goodsModalVisible: false,
      corpList: [],
      keyboard: false,
      enterpriseType: false,
      corpModalVisible: false,
      previewModalVisible: false,
      applyCompanyInfoVO: {},
      loaded: false,
      optionCheck: {
        modalVisible: false,
        data: [],
        checkObj: {}
      },
      countryInfo: null,
      checkCountryInfo: {
        areaId: '86',
        areaName: '中国'
      },
      defaultStaff: {},
      dateTypeObj: {
        registerDate: '',
        expireDate: '',
      },
      areaModalProp: {
        addressInfo: null,
      },
      offsetY: 0
    }

    this.choice = props.navigation.state.params.choice || {};
    console.log('choice', this.choice)
    this.selectPhotoTapped = this.selectPhotoTapped.bind(this);
    this.creditFileHandle = this.creditFileHandle.bind(this);
    this.setAddress = this.setAddress.bind(this);
    this.renderCorpView = this.renderCorpView.bind(this);
    this._keyboardDidShow = this._keyboardDidShow.bind(this);
    this._keyboardDidHide = this._keyboardDidHide.bind(this);
    this._setEditInfo = this._setEditInfo.bind(this);
    this._setReference = this._setReference.bind(this);
    this._setCountryParams = this._setCountryParams.bind(this);

    this.sendData = responseDataParams || {
      step: 1,
      bizType: 'COMPANY_BASE_ADD',
      companyInfoVO: {
        companyType: null,
        linkPhone: null,
        creditFile: null,
        companyNature: null,
      },
      corpTypeList: [],
      categoryList: [],
      acctList: [],
      staffCompanyList: [],
      comments: '',
      checkGoods: []
    };
    this.sendData.step = 1;

    modalPicDelCfg.picPress = () => {
      modalPicDelCfg.visible = false;
      modalPicDelCfg.uri = null;
      this.setState({
        previewModalVisible: false,
      });
    }
    modalPicDelCfg.delPress = () => {
      modalPicDelCfg.visible = false;
      modalPicDelCfg.uri = null;
      this.setState({
        previewModalVisible: false,
        creditFileSource: null,
      });
      delete this.sendData.companyInfoVO.creditFile;
    }

    this.goodsModalProp = {
      visible: false,
      goodsSelected: this.state.good,
      cancelPress: () => {
        this.goodsModalProp.visible = false;
        this.setState({
          goodsModalVisible: false,
        });
      },
      confirmPress: async (category3Selected) => {
        const { checkGoods } = this.state;
        this.goodsModalProp.visible = false;
        this.setState({
          goodsModalVisible: false,
        });
        const goodsCateArray = [];
        console.log('category3Selected', category3Selected)
        for (let key in category3Selected) {
          if (category3Selected[key]['check']) {
            goodsCateArray.push({
              goodsCateId: key,
              objectId: key,
              goodsCateName: category3Selected[key]['goodsCateName'],
              id: category3Selected[key]['id'] || null,
              companyId: category3Selected[key]['companyId'] || null,
              check: category3Selected[key]['check'],
            });
          }
        }
        console.log('goodsCateArray', goodsCateArray)
        if (goodsCateArray.length) {
          this.setGoodsChecked(goodsCateArray);

          let goodsList = [];
          goodsCateArray.map(item => {
            const { goodsCateName } = item;
            if (goodsCateName !== '选择全部') {
              goodsList.push(item);
            }
          });
          console.log('goodsList', goodsList)
          this.sendData.goodsList = goodsList;
          const procuctArray = this.sendData.goodsList.map(item => {
            const { goodsCateName } = item;
            return goodsCateName;
          });
          this.setState({
            productText: procuctArray.join(','),
          });

          requireQualification = {};
          const qualificationData = await HTTP.POST(API_GENERATE(API.FIND_QUALIFICA_BYCATE), this.sendData.goodsList);
          const { countryInfo } = this.props.navigation.state.params;
          if (countryInfo && countryInfo.areaId) {
            if (this.props.navigation.state.params.countryInfo.areaId === '86') {
              qualificationData.forEach(item => {
                const { qualificationCode } = item;
                requireQualification[qualificationCode] = qualificationCode;
              });
            }
          } else {
            qualificationData.forEach(item => {
              const { qualificationCode } = item;
              requireQualification[qualificationCode] = qualificationCode;
            });
          }

        } else {
          this.sendData.goodsList = [];
          requireQualification = {};
          this.setState({
            productText: '请选择',
          });
        }
      }
    }
  }

  async componentWillMount() {
    const { params } = this.props.navigation.state;
    const account = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
    this.account = JSON.parse(account);
    if (this.account) {
      this.defaultStaff = {};
      this.defaultStaff[this.account.userId] = {
        staffId: this.account.userId,
        staffName: this.account.userName
      };
      this.setState({
        defaultStaff: this.defaultStaff,
        userName: this.account.userName,
        userId: this.account.userId
      })
    }
    this._getCountryInfo();
    this._getAddressInfo();

    if (params.companyId) {
      this._getEnterpriseDetail(params);
    }

    //企业类型
    companyTypeListData = await Dictionary.get('COMPANY_PROP');

    companyCapitalListData = await Dictionary.get('COMPANY_CAPITAL_PROP');

    corpResult = await Dictionary.get('EC_CORP_TYPE');
    let saleCorp = [];
    let notSaleCorp = [];
    for (let i = 0; i < corpResult.length; i++) {
      //业务员只展示‘客户’‘供应商’,非业务员只展示除去‘客户’‘供应商’的关系
      if (corpResult[i].dictKey == '1' || corpResult[i].dictKey == '2') {
        saleCorp.push({
          key: corpResult[i].dictKey,
          btnText: corpResult[i].dictName,
          isChecked: false,
        });
      } else {
        notSaleCorp.push({
          key: corpResult[i].dictKey,
          btnText: corpResult[i].dictName,
          isChecked: false,
        });
      }
    }

    this.setState({
      corpList: this.account.isBizer == '1' ? saleCorp : notSaleCorp
    });

    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);

    this.props.navigation.setParams({
      setReference: this._setReference,
      setAddress: this.setAddress,
      setEditInfo: this._setEditInfo,
      setCountryParams: this._setCountryParams,
      countryInfo: this.state.checkCountryInfo,
    });
  }

  componentWillUnmount() {
    try {
      this.setState({
        loaded: false,
        modalAreaVisible: false
      });
      this.keyboardDidShowListener.remove();
      this.keyboardDidHideListener.remove();
    } catch (error) {
      console.log(error);
    }
  }

  //商品有数据时，讲数据传给商品组建，以显示选中状态
  setGoodsChecked(goodsList) {
    let checkGoods = goodsList || [];
    let good = {};
    if (checkGoods.length > 0) {
      const { objectId } = checkGoods;
      checkGoods.map(item => {
        good[item.objectId] = item;
      });
      for (let key in good) {
        good[key].id = good[key].id;
        good[key].goodsCateName = good[key].goodsCateName;
        good[key].goodsCateId = good[key].objectId;
        good[key].objectId = good[key].objectId;
        good[key].companyId = good[key].companyId;
        good[key]['check'] = true;
      }
      this.setState({
        good,
        checkGoods
      });
    }
  }

	/**
	 * 草稿跳转进来，查询企业详情，覆盖页面的值
	 * @param {企业id}} id 
	 */
  async _getEnterpriseDetail(params) {
    this.setState({
      loaded: true
    })
    const responseData = await HTTP.POST(API_GENERATE(API.GET_CUSTOMER_APPLY_DETAIL), {
      isPage: 1, //1
      companyId: params.companyId,
      id: params.id,
      corpId: this.choice.corpId
    });
    this.setState({
      loaded: false,
    })
    if (responseData) {
      let corpTypeText = [];
      let productText = [];
      const userNameList = [];
      const corpList = [];

      this.setGoodsChecked(responseData.goodsList);

      this.sendData = responseData;
      this.sendData.step = 1;

      //社会统一信用证图片预览
      if (responseData.companyInfoVO && responseData.companyInfoVO.creditFile && responseData.companyInfoVO.creditFile.length > 0) {
        const { provinceName, cityName, areaName } = responseData.companyInfoVO;
        this.areaText = `${provinceName || '-'}，${cityName || '-'}，${areaName || '-'}`;
        const fetchCreditFileAsync = await HTTP.GET(API_GENERATE(API.GET_IMG_VIEW), { fileId: responseData.companyInfoVO.creditFile }, {
          rejectError: false,
          handleError: true,
        }, 30000);
        if (fetchCreditFileAsync && fetchCreditFileAsync.image) {
          let { image } = fetchCreditFileAsync;
          if (image && image.length) {
            this.setState({
              creditFileSource: { uri: image }
            });
          }
        }
      }

      //合作类型
      if (responseData.corpTypeList && responseData.corpTypeList.length) {
        let corpTextArray = [];

        responseData.corpTypeList.forEach(item => {
          corpTextArray.push(item.corpTypeName);

          corpList = this.state.corpList.map(corpListItem => {
            if (corpListItem.key == item.corpType) {
              corpListItem.isChecked = true;
              corpListItem.id = item.id;
              corpListItem.companyId = item.companyId;
            }
            return corpListItem;
          });
          this.setState({
            corpList
          });
        });

        corpTypeText = corpTextArray.length > 0 ? corpTextArray.join(',') : '请选择';
      }

      //业务经办人
      if (responseData.staffCompanyList && responseData.staffCompanyList.length) {
        this._setReferenceCheck(responseData.staffCompanyList);
      }

      //商品
      if (responseData.goodsList && responseData.goodsList.length > 0) {
        const procuctArray = responseData.goodsList.map(item => {
          const { goodsCateName } = item;
          return goodsCateName;
        });

        productText = procuctArray.join(',');

        const qualificationData = await HTTP.POST(API_GENERATE(API.FIND_QUALIFICA_BYCATE), responseData.goodsList);
        const { countryInfo } = this.props.navigation.state.params;
        if (countryInfo && countryInfo.areaId) {
          if (this.props.navigation.state.params.countryInfo.areaId === '86') {
            qualificationData.forEach(item => {
              const { qualificationCode } = item;
              requireQualification[qualificationCode] = qualificationCode;
            });
          }
        } else {
          qualificationData.forEach(item => {
            const { qualificationCode } = item;
            requireQualification[qualificationCode] = qualificationCode;
          });
        }
      }


      this.setState({
        checkCountryInfo: {
          areaId: responseData.companyInfoVO ? responseData.companyInfoVO.countryCode : this.state.checkCountryInfo.areaId,
          areaName: responseData.companyInfoVO ? responseData.companyInfoVO.countryName : this.state.checkCountryInfo.areaName,
        },
        applyCompanyInfoVO: responseData.companyInfoVO || {},
        companyNatureText: responseData.companyInfoVO ? responseData.companyInfoVO.companyNatureName : '',
        companyTypeText: responseData.companyInfoVO ? responseData.companyInfoVO.companyTypeName : '',
        corpTypeText: corpTypeText.length > 0 ? corpTypeText : '请选择',
        productText: productText.length > 0 ? productText : '请选择',
        dateTypeObj: {
          registerDate: responseData.companyInfoVO ? responseData.companyInfoVO.registerDate : '',
          expireDate: responseData.companyInfoVO ? responseData.companyInfoVO.expireDate : ''
        },
        areaText: this.areaText
      })
    }
  }

  _setReference(users) {
    this.userIdsChecked = {};
    const userNameList = [];
    const newStaffCompanyList = [];
    users.map((user) => {
      const { staffId, staffName, check } = user;
      if (check) {
        userNameList.push(staffName);
        this.userIdsChecked[staffId] = user;
        newStaffCompanyList.push(user);
      }
    });
    this.sendData.staffCompanyList = newStaffCompanyList;

    this.usersFromStep1 = newStaffCompanyList;

    this.setState({
      referenceStr: userNameList.join(',')
    });
  }

  _setReferenceCheck(staffCompanyList) {
    this.userIdsChecked = {};
    const userNameList = [];
    this.usersFromStep1 = staffCompanyList.map((user) => {
      const { staffId, staffName } = user;
      userNameList.push(staffName);
      user['check'] = true;
      this.userIdsChecked[staffId] = user;
      return user;
    });

    this.sendData.staffCompanyList = this.usersFromStep1;

    this.setState({
      referenceStr: userNameList.join(','),
    })
  }

  _setCountryParams(checkCountryInfo) {
    this.setState({
      checkCountryInfo
    })
  }

	/**
	 * 获取省市区
	*/
  async _getCountryInfo() {
    const countryListStorage = await StorageHelper.get(STORAGE_CONSTANT.COUNTRY_INFO);
    if (countryListStorage) {
      this.countryInfo = JSON.parse(countryListStorage);
    } else {
      this.countryInfo = await HTTP.GET(API_GENERATE(API.GET_AREA_LIST_BY_LEVEL), { nodeLevel: 1 });

      if (this.countryInfo) {
        StorageHelper.set(STORAGE_CONSTANT.COUNTRY_INFO, this.countryInfo);
      }
    }
    this.setState({
      countryInfo: this.countryInfo
    })
  }
  _getAddressInfo() {
    let mapData = require('../../../data/map.json');
    this.setState({
      areaModalProp: {
        addressInfo: mapData.data,
        cancelPress: () => {
          this.setState({
            modalAreaVisible: false
          });
        },
        confirmPress: (data) => {
          const { province, city, area } = data;
          console.log(city.areaName)
          this.areaText = `${province.areaName || '-'}，${city.areaName || '-'}，${area.areaName || '-'}`;

          this.sendData.companyInfoVO.areaCode = area.areaId;

          this.setState({
            modalAreaVisible: false,
            areaText: this.areaText
          });
        },
      },
    })
  }
  _keyboardDidShow() {
    this.setState({
      keyboard: true,
    });
  }

  _keyboardDidHide() {
    this.setState({
      keyboard: false,
    });
  }

  _setTimeCallback = (date, type) => {
    const { dateTypeObj } = this.state;
    dateTypeObj[type] = date;
    this.sendData.companyInfoVO.registerDate = dateTypeObj['registerDate'];
    this.sendData.companyInfoVO.expireDate = dateTypeObj['expireDate'];
    this.setState({
      dateTypeObj
    })
  }

  render() {
    const { corpTypeText, productText, keyboard, applyCompanyInfoVO, referenceStr, defaultStaff, userName, userId,
      optionCheck, companyNatureText, companyTypeText, countryInfo, checkCountryInfo, goodsModalVisible } = this.state;
    const { creditFileSource, dateTypeObj, areaModalProp, modalAreaVisible } = this.state;
    bankLabel = checkCountryInfo.areaId === '86' ? '必填' : '选填';
    let uploadView = (
      <TouchableOpacity style={enterpriseStyles.attachment} onPress={() => {
        this.selectPhotoTapped('creditFile', this.creditFileHandle, 'BIZ_LICENSE');
      }} activeOpacity={0.5} >
        <View style={enterpriseStyles.cover} >
          <Image source={uploadPic} style={{ width: '100%', height: '100%' }} />
        </View>
      </TouchableOpacity>
    );
    if (creditFileSource) {
      uploadView = (
        <TouchableOpacity style={enterpriseStyles.attachment} onPress={() => {
          modalPicDelCfg.visible = true;
          modalPicDelCfg.uri = creditFileSource.uri;
          modalPicDelCfg.fileId = fileIdObj[creditFileSource.uri];
          this.setState({
            previewModalVisible: true
          });
        }} activeOpacity={0.5} >

          <Image source={creditFileSource} style={enterpriseStyles.cover} />
        </TouchableOpacity>
      );
    }
    const keyboardStyle = keyboard ? { top: -210 * scale } : null;
    const corpView = this.renderCorpView();

    return (
      <ScrollView style={styles.scrollView} onScroll={(e) => {
        let offsetY = e.nativeEvent.contentOffset.y; //滑动距离
        this.setState({
          offsetY
        })
      }}>
        <View style={styles.container}>
          {
            goodsModalVisible ? <ProductSelectAll {...this.goodsModalProp} /> : null
          }

          {corpView}
          <ModalPicDelComponent {...modalPicDelCfg} />
          <View style={[styles.wrap, keyboardStyle]}>
            <Common type="headCloes" callBack={() => {
              Alert.alert(
                '提示',
                '确定放弃创建客户吗?',
                [
                  { text: '取消', onPress: () => console.log('Cancel Pressed') },
                  { text: '确定', onPress: () => { this.props.navigation.goBack() } },
                ],
                { cancelable: false }
              )
            }} imgStyle={{ marginBottom: 14 * scale }} />

            <Text style={enterpriseStyles.titleText}>企业信息</Text>
            {/* <Text style={enterpriseStyles.businessGroup}>业务组织：{'浙江石化销售'}</Text> */}
            <View style={enterpriseStyles.field}>
              <Text style={enterpriseStyles.lableText}>国家(必填)</Text>
              <TouchableOpacity activeOpacity={.5} style={enterpriseStyles.optionView} onPress={() => {
                const { navigate } = this.props.navigation;
                Keyboard.dismiss();
                navigate('CountryListPage', {
                  countryInfo
                });
              }}>
                <Text style={enterpriseStyles.text}>
                  {checkCountryInfo.areaName}
                </Text>
                <Image source={arrowLeft} style={enterpriseStyles.arrowLeft} />
              </TouchableOpacity>
            </View>

            <Text style={enterpriseStyles.lableText}>统一社会信用证(支持jpg、png等图片格式，必填)</Text>
            <View style={enterpriseStyles.tip}>
              <Text style={{ color: '#cf8300', fontSize: 12 * scale, height: 14 * scale }}>手机拍电脑会导致图片不清晰进而识别功能减弱</Text>
            </View>
            <View style={enterpriseStyles.attachmentRow}>
              {uploadView}
            </View>

            <View style={enterpriseStyles.field}>
              <Text style={enterpriseStyles.lableText}>企业名称(必填)</Text>
              <TextInput
                ref="name1Input"
                style={enterpriseStyles.textInput}
                underlineColorAndroid='transparent'
                returnKeyType='done'
                keyboardType='default'
                placeholder={"请输入"}
                placeholderTextColor="#404040"
                maxLength={100}
                editable={true}
                defaultValue={applyCompanyInfoVO.companyName}
                onChangeText={(txt) => {
                  this.sendData.companyInfoVO.companyName = txt;
                }}
                onBlur={() => {
                  this.checkCompany({ name: this.sendData.companyInfoVO.companyName, code: null });
                }}
              />
            </View>

            {
              this.state.organName ?
                <View style={{ marginBottom: 12 * scale }}>
                  <Text style={enterpriseStyles.checkCompanyText}>该企业已存在{this.state.organName}</Text>
                </View>
                : null
            }

            <View style={enterpriseStyles.field}>
              <Text style={enterpriseStyles.lableText}>法定代表人(必填)</Text>
              <TextInput
                ref="legalNameInput"
                style={enterpriseStyles.textInput}
                underlineColorAndroid='transparent'
                returnKeyType='done'
                keyboardType='default'
                placeholder={"请输入"}
                placeholderTextColor="#404040"
                maxLength={100}
                editable={true}
                defaultValue={applyCompanyInfoVO.legalName}
                onEndEditing={() => { }}
                onChangeText={(txt) => {
                  this.sendData.companyInfoVO.legalName = txt;
                }}
              />
            </View>

            <View style={enterpriseStyles.field}>
              <Text style={enterpriseStyles.lableText}>注册资本({bankLabel})</Text>
              <View style={{ flexDirection: 'row', alignItems: 'center', }}>
                <TextInput
                  ref="registerFundInput"
                  style={[enterpriseStyles.textInput, { flex: 1 }]}
                  underlineColorAndroid='transparent'
                  keyboardType='numeric'
                  placeholder={"请输入整数，如1000"}
                  placeholderTextColor="#404040"
                  maxLength={100}
                  editable={true}
                  defaultValue={applyCompanyInfoVO.registerFund || ''}
                  onEndEditing={() => {
                    // if (!this.sendData.companyInfoVO.creditCode) {
                    // 	this.refs.creditCodeInput.focus();
                    // }
                  }}
                  onChangeText={(txt) => {
                    this.sendData.companyInfoVO.registerFund = txt;
                  }}
                /><Text style={enterpriseStyles.text}>万元</Text></View>
            </View>

            <View style={enterpriseStyles.field}>
              <Text style={enterpriseStyles.lableText}>统一社会信用代码(必填)</Text>
              <TextInput
                ref="creditCodeInput"
                style={enterpriseStyles.textInput}
                underlineColorAndroid='transparent'
                returnKeyType='done'
                keyboardType='default'
                placeholder={"请输入"}
                placeholderTextColor="#404040"
                maxLength={100}
                editable={true}
                defaultValue={applyCompanyInfoVO.creditCode}
                onChangeText={(txt) => {
                  if (!/^[a-zA-Z0-9]*$/.test(txt)) {
                    this.refs.creditCodeInput.clear();
                    return;
                  }
                  this.sendData.companyInfoVO.creditCode = txt;
                }}
                onBlur={() => {
                  this.checkCompany({ name: null, code: this.sendData.companyInfoVO.creditCode });
                }}
              />
            </View>

            {
              this.state.creditName ?
                <View style={{ marginBottom: 12 * scale }}>
                  <Text style={enterpriseStyles.checkCompanyText}>该企业已存在{this.state.creditName}</Text>
                </View>
                : null
            }

            <View style={enterpriseStyles.field}>
              <Text style={enterpriseStyles.lableText}>注册日期(必填)</Text>
              <DatePicker
                style={{ width: 200 }}
                date={dateTypeObj['registerDate']}
                mode="date"
                placeholder="请选择"
                format="YYYY-MM-DD"
                minDate={'1970-01-01'}
                maxDate="2100-12-01"
                confirmBtnText="确认"
                cancelBtnText="取消"
                customStyles={{
                  dateIcon: { opacity: 0, width: 0 },
                  dateInput: { marginLeft: 0, borderWidth: 0, alignItems: 'flex-start' },
                  placeholderText: {
                    fontSize: 14 * scale,
                    color: '#404040'
                  }
                }}
                onDateChange={(date) => { this._setTimeCallback(date, 'registerDate'); }}
              />
            </View>

            <View style={enterpriseStyles.field}>
              <Text style={enterpriseStyles.lableText}>营业执照过期日期(必填)</Text>
              <View style={[styles.expireDateView]}>
                <DatePicker
                  style={{ width: 240 }}
                  date={dateTypeObj['expireDate']}
                  mode="date"
                  placeholder="请选择"
                  format="YYYY-MM-DD"
                  minDate={new Date()}
                  maxDate="2100-12-01"
                  confirmBtnText="确认"
                  cancelBtnText="取消"
                  customStyles={{
                    dateIcon: { opacity: 0, width: 0 },
                    dateInput: {
                      marginLeft: 0, borderWidth: 0, alignItems: 'flex-start'
                    },
                    placeholderText: {
                      fontSize: 14 * scale,
                      color: '#404040'
                    }
                  }
                  }
                  onDateChange={(date) => { this._setTimeCallback(date, 'expireDate'); }}
                />
                <Text style={styles.expireDateText} onPress={() => {
                  this._setTimeCallback('2099-12-31', 'expireDate');
                }}>长期有效</Text>
              </View>
            </View>

            <View style={enterpriseStyles.field}>
              <Text style={enterpriseStyles.lableText}>资本性质(必填)</Text>
              <TouchableOpacity activeOpacity={.5} style={enterpriseStyles.optionView} onPress={() => {
                Keyboard.dismiss();
                this.setState({
                  optionCheck: {
                    title: '资本性质',
                    data: companyCapitalListData,
                    modalVisible: true,
                    checkObj: optionCheck.checkObj,
                    checkType: 'companyNature',
                    onBgPress: () => {
                      this.onModalBgPress(companyCapitalListData);
                    },
                    onPress: (index) => {
                      this.onModalItemPress('companyNature', companyCapitalListData, index);
                    }
                  }
                });

              }}>
                <Text style={enterpriseStyles.text}>{companyNatureText}</Text>
                <Image source={arrowLeft} style={enterpriseStyles.arrowLeft} />
              </TouchableOpacity>
            </View>

            <View style={enterpriseStyles.field}>
              <Text style={enterpriseStyles.lableText}>企业性质(必填)</Text>
              <TouchableOpacity activeOpacity={.5} style={enterpriseStyles.optionView} onPress={() => {
                Keyboard.dismiss();
                this.setState({
                  optionCheck: {
                    title: '企业属性',
                    data: companyTypeListData,
                    modalVisible: true,
                    checkObj: optionCheck.checkObj,
                    checkType: 'companyType',
                    onBgPress: () => {
                      this.onModalBgPress(companyTypeListData);
                    },
                    onPress: (index) => {
                      this.onModalItemPress('companyType', companyTypeListData, index);
                    }
                  }
                });
              }}>
                <Text style={enterpriseStyles.text}>{companyTypeText}</Text>
                <Image source={arrowLeft} style={enterpriseStyles.arrowLeft} />
              </TouchableOpacity>
            </View>

            <View style={enterpriseStyles.field}>
              <Text style={enterpriseStyles.lableText}>合作关系(必填)</Text>
              <TouchableOpacity activeOpacity={.5} style={enterpriseStyles.optionView} onPress={() => {
                Keyboard.dismiss();
                this.setState({ corpModalVisible: true, });
              }} >
                <Text style={enterpriseStyles.text}>{corpTypeText}</Text>
                <Image source={arrowLeft} style={enterpriseStyles.arrowLeft} />
              </TouchableOpacity>
            </View>

            <View style={enterpriseStyles.field}>
              <Text style={enterpriseStyles.lableText}>商品(必填)</Text>
              <TouchableOpacity activeOpacity={.5} style={enterpriseStyles.optionView} onPress={() => {
                const { goodsModalVisible } = this.state;
                this.setState({
                  goodsModalVisible: true
                });
                this.goodsModalProp.visible = true;
                this.goodsModalProp.goodsSelected = this.state.good;
                Keyboard.dismiss();
              }}>
                <Text style={enterpriseStyles.text}>{productText.length > 32 ? productText.substr(0, 32) + '...' : productText}</Text>
                <Image source={arrowLeft} style={enterpriseStyles.arrowLeft} />
              </TouchableOpacity>
            </View>

            <View style={enterpriseStyles.field}>
              <Text style={enterpriseStyles.lableText}>业务经办人</Text>
              <TouchableOpacity activeOpacity={1} style={enterpriseStyles.optionView}
              // onPress={() => {
              //   const { navigate } = this.props.navigation;
              //   Keyboard.dismiss();
              //   navigate('ReferenceListPage', {
              //     goBackPage: 'EnterpriseCreateBaseInfo',
              //     title: '业务经办人',
              //     userIdsChecked: this.userIdsChecked || defaultStaff,
              //     usersFromStep1: this.usersFromStep1 || [{
              //       staffId: userId,
              //       staffName: userName,
              //       check: true
              //     }],
              //   });
              // }}
              >
                <Text style={enterpriseStyles.text}>{referenceStr || userName}</Text>
                {/* <Image source={arrowLeft} style={enterpriseStyles.arrowLeft} /> */}
              </TouchableOpacity>
            </View>


            <View style={enterpriseStyles.field}>
              <Text style={enterpriseStyles.lableText}>企业注册地址(必填)</Text>
              <View style={enterpriseStyles.textInputView}>
                <TouchableOpacity style={styles.inputRowRight} activeOpacity={.5} onPress={() => {
                  this.setState({
                    modalAreaVisible: true
                  });
                }}>
                  <Text style={enterpriseStyles.text}>{this.state.areaText || '请选择省市区'}</Text>
                  <Image source={arrowLeft} style={enterpriseStyles.arrowLeft} />
                </TouchableOpacity>
                <TextInput
                  ref="detailAddress"
                  style={[enterpriseStyles.textInput, { flex: 1, flexWrap: 'wrap' }]}
                  underlineColorAndroid='transparent'
                  returnKeyType='done'
                  keyboardType='default'
                  placeholder={"详细地址"}
                  placeholderTextColor="#404040"
                  editable={true}
                  defaultValue={applyCompanyInfoVO.registAddress}
                  onChangeText={(txt) => {
                    this.sendData.companyInfoVO.registAddress = txt;
                  }}
                />

              </View>
            </View>


            <View style={enterpriseStyles.footBtnCell}>
              <Text></Text>
              <TouchableOpacity style={enterpriseStyles.footBtn} onPress={this._didPressNextBtn.bind(this)} activeOpacity={0.5} >
                <Text style={enterpriseStyles.footBtnText}>下一步</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
        <OptionCheck {...optionCheck} />

        {areaModalProp.addressInfo ? <ModalAreaComponent {...areaModalProp} selectCustom={true} visible={modalAreaVisible} /> : null}

        {
          this.state.loaded ?
            <View style={{ position: 'absolute', height: GLOBAL.SCREEN_HEIGHT, width: GLOBAL.SCREEN_WIDTH, top: this.state.offsetY }}>
              <PageStatusIndex status='loading' />
            </View>
            : null
        }
      </ScrollView >
    );
  }

  async checkCompany(params) {
    const sendData = {};
    if (params.name) {
      sendData.companyName = params.name;
    }
    if (params.code) {
      sendData.creditCode = params.code;
    }
    const checkCompanyResoult = await HTTP.GET(API_GENERATE(API.CHECK_COMPANY_CREDITCODE), sendData, {
      rejectError: false,
      handerError: false
    });

    if (checkCompanyResoult && checkCompanyResoult.companyId) {
      this.setState({
        organName: params.name ? checkCompanyResoult.organName : this.state.organName,
        creditName: params.code ? checkCompanyResoult.organName : this.state.creditName,
      })
    } else {
      this.setState({
        organName: params.name ? '' : this.state.organName,
        creditName: params.code ? '' : this.state.creditName,
      })
    }
  }

  onModalBgPress(data) {
    const { optionCheck } = this.state;

    this.setState({
      optionCheck: {
        modalVisible: false,
        data: data,
        checkObj: optionCheck.checkObj,
      }
    })
  }

  onModalItemPress(type, data, index) {
    const { optionCheck } = this.state;
    const { dictName, dictKey } = data[index];
    optionCheck.checkObj[type] = { dictKey };
    this.setState({
      optionCheck: {
        checkObj: optionCheck.checkObj,
        data: data,
        modalVisible: false,
      },
      companyTypeText: type === 'companyType' ? dictName : this.state.companyTypeText,
      companyNatureText: type === 'companyNature' ? dictName : this.state.companyNatureText,
    });
    this.sendData.companyInfoVO.companyType = type === 'companyType' ? dictKey : this.sendData.companyInfoVO.companyType;
    this.sendData.companyInfoVO.companyNature = type === 'companyNature' ? dictKey : this.sendData.companyInfoVO.companyNature;
  }

  _setEditInfo(obj) {
    this.sendData = obj;
    this.sendData.companyInfoVO.companyId = obj.companyInfoVO.companyId;
    this.sendData.companyInfoVO.id = obj.companyInfoVO.id;
    this.sendData.companyInfoVO.taskId = obj.taskId;
    this.sendData.id = obj.companyInfoVO.id;
    this.sendData.taskId = obj.taskId;
    // this.sendData.addressList = obj.addressList;
    this.setGoodsChecked(obj.goodsList);
    this._setReferenceCheck(obj.staffCompanyList);
  }

  async _didPressNextBtn() {
    Keyboard.dismiss();

    const { companyInfoVO = {}, staffCompanyList, contactorList, goodsList, corpTypeList } = this.sendData;
    const { registerFund, legalName, companyName, creditCode, registAddress, countryCode, companyNature,
      companyType, registerDate, expireDate, areaCode } = companyInfoVO;
    if (ValidateDataUtil.isEmpty(companyInfoVO)) {
      this.sendData.companyInfoVO = {};
    }
    this.sendData.companyInfoVO.countryCode = this.state.checkCountryInfo.areaId;
    this.sendData.companyInfoVO.countryName = this.state.checkCountryInfo.areaName;

    if (staffCompanyList && staffCompanyList.length) { } else {
      this.sendData.staffCompanyList = [{
        staffId: this.state.userId,
        staffName: this.state.userName
      }]
    }

    if (ValidateDataUtil.isEmpty(companyName)) {
      Alert.alert('请填写企业名称');
      this.refs.name1Input.focus();
      return;
    }
    if (ValidateDataUtil.isEmpty(legalName)) {
      Alert.alert('请输入法定代表人');
      this.refs.legalNameInput.focus();
      return;
    }
    if (this.sendData.companyInfoVO.countryCode === '86' && !MethodUtil.checkRate(registerFund)) {
      Alert.alert('请输入正确格式的注册资本');
      this.refs.registerFundInput.focus();
      return;
    }

    if (ValidateDataUtil.isEmpty(creditCode)) {
      Alert.alert('请输入统一社会信用代码');
      this.refs.creditCodeInput.focus();
      return;
    }

    if (!(/^[a-zA-Z0-9]+$/).test(creditCode)) {
      Alert.alert('统一社会信用代码输入错误');
      this.refs.name1Input.focus();
      return;
    }
    if (ValidateDataUtil.isEmpty(registerDate)) {
      Alert.alert('请输入注册日期');
      return;
    }
    if (ValidateDataUtil.isEmpty(expireDate)) {
      Alert.alert('请输入营业执照过期日期');
      return;
    }
    if (ValidateDataUtil.isEmpty(companyNature)) {
      Alert.alert('请选择资本性质');
      return;
    }

    if (ValidateDataUtil.isEmpty(companyType)) {
      Alert.alert('请选择企业性质');
      return;
    }

    if (!corpTypeList || !corpTypeList.length) {
      Alert.alert('请选择合作关系');
      return;
    }

    if (!goodsList || goodsList.length === 0) {
      Alert.alert('请选择商品');
      return;
    }
    if (ValidateDataUtil.isEmpty(areaCode)) {
      Alert.alert('请选择省市区到区级');
      return;
    }
    if (ValidateDataUtil.isEmpty(registAddress)) {
      Alert.alert('请填写企业注册地址');
      this.refs.detailAddress.focus();
      return;
    }

    if (this.requesting) return;
    this.setState({ loaded: true });
    this.requesting = true;
    this.sendData.corpId = this.choice.corpId;
    const responseData = await HTTP.POST(API_GENERATE(API.ADD_APPLY_COMPANY), this.sendData);

    this.setState({
      loaded: false
    })
    if (responseData) {
      this.requesting = false;
      const { navigate } = this.props.navigation;
      navigate('EnterpriseCreateAdditionInfo', {
        requireQualification,
        responseData,
        productText: this.state.productText,
        corpTypeList: this.sendData.corpTypeList,
        creditCode: this.sendData.companyInfoVO.creditCode,
        choice: this.choice
      });
    } else {
      this.requesting = false;
    }
  }

	/**
	* 上传图片
	* @param {String} attachment 统一社会信用证文件 分类
	* @param {function} handle
	* @param {String} ocrType 分类
				*/
  selectPhotoTapped(attachment, handle, ocrType) {
    const options = {
      title: '请选择图片来源',
      cancelButtonTitle: '取消',
      takePhotoButtonTitle: '拍照',
      chooseFromLibraryButtonTitle: '相册图片',
      quality: 1,
      maxWidth: 1080,
      maxHeight: 1080,
      storageOptions: {
        skipBackup: true,
        // path: 'images'
      },
      mediaType: 'photo',
    };
    ImagePicker.showImagePicker(options, async (response) => {
      if (response.didCancel) {
        return;
      }
      else if (response.error) {
        return;
      }
      else if (response.customButton) {
        return;
      }

      const uploadImgObj = {
        imgUrl: { uri: response.uri },
        url: API_GENERATE(API.IMG_UPLOAD),
      }
      if (ocrType && ocrType.length) {
        uploadImgObj.ocrType = ocrType;
        uploadImgObj.isOcr = 1;
      } else {
        uploadImgObj.isOcr = 0
      }
      this.setState({
        loaded: true
      });
      let responseData = await Upload.uploadImg(uploadImgObj);
      if (responseData) {
        fileIdObj[response.uri] = responseData.fileId;
        this.setState({
          creditFileSource: { uri: response.uri },
        });
        if (responseData.fileId && handle && (typeof (handle) == 'function')) {
          handle(responseData);
        }
      }
      this.setState({
        loaded: false
      });
    });
  }

	/**
	 * 统一社会信用证
	* @param {object} data
			*/
  creditFileHandle(data) {
    const { fileId, applyCompanyInfoVO } = data;
    if (applyCompanyInfoVO) {
      //企业名称
      if (applyCompanyInfoVO.companyName && applyCompanyInfoVO.companyName.length) {
        this.sendData.companyInfoVO.companyName = applyCompanyInfoVO.companyName;
        this.checkCompany({ name: this.sendData.companyInfoVO.companyName, code: null });
      } else {
        applyCompanyInfoVO.companyName = this.sendData.companyInfoVO.companyName || '';
      }
      //法定代表人
      if (applyCompanyInfoVO.legalName && applyCompanyInfoVO.legalName.length) {
        this.sendData.companyInfoVO.legalName = applyCompanyInfoVO.legalName;
      } else {
        applyCompanyInfoVO.legalName = this.sendData.companyInfoVO.legalName || '';
      }
      //注册日期
      if (applyCompanyInfoVO.registerDate && applyCompanyInfoVO.registerDate.length) {
        this.sendData.companyInfoVO.registerDate = applyCompanyInfoVO.registerDate;
      } else {
        applyCompanyInfoVO.registerDate = this.sendData.companyInfoVO.registerDate || '';
      }
      //营业执照过期日期
      if (applyCompanyInfoVO.expireDate && applyCompanyInfoVO.expireDate.length) {
        this.sendData.companyInfoVO.expireDate = applyCompanyInfoVO.expireDate;
      } else {
        applyCompanyInfoVO.expireDate = this.sendData.companyInfoVO.expireDate || '';
      }
      //注册资本
      if (applyCompanyInfoVO.registerFund && applyCompanyInfoVO.registerFund.length) {
        this.sendData.companyInfoVO.registerFund = applyCompanyInfoVO.registerFund;
      } else {
        applyCompanyInfoVO.registerFund = this.sendData.companyInfoVO.registerFund || '';
      }
      //统一信用证
      if (applyCompanyInfoVO.creditCode && applyCompanyInfoVO.creditCode.length) {
        this.sendData.companyInfoVO.creditCode = applyCompanyInfoVO.creditCode;
        this.checkCompany({ name: null, code: this.sendData.companyInfoVO.creditCode });
      } else {
        applyCompanyInfoVO.creditCode = this.sendData.companyInfoVO.creditCode || '';
      }
      //注册地址
      if (applyCompanyInfoVO.registAddress && applyCompanyInfoVO.registAddress.length) {
        this.sendData.companyInfoVO.registAddress = applyCompanyInfoVO.registAddress;
      } else {
        applyCompanyInfoVO.registAddress = this.sendData.companyInfoVO.registAddress || '';
      }

      this.setState({
        applyCompanyInfoVO,
      });
    }
    this.sendData.companyInfoVO.creditFile = fileId;

    if (!fileId) {
      ToastUtil.showInfo('上传失败，请稍后再试');
      this.setState({
        creditFileSource: null,
      });
    }
  }

  setAddress(addressParams) {

    let { address, poiInfo } = addressParams;

    if (!poiInfo) {
      poiInfo = '';
    }

    addressObj = addressParams;
    addressObj.detailAddress = address + ' ' + poiInfo;

    if (this.sendData.companyInfoVO && this.sendData.companyInfoVO.linkPhone) {
      addressObj.mobileNo = this.sendData.companyInfoVO.linkPhone
    }

    this.sendData.companyInfoVO.registAddress = address + poiInfo;

    const detailAddress = address + ' ' + poiInfo;
    this.setState({
      detailAddress,
      applyCompanyInfoVO: {
        registAddress: detailAddress
      }
    });
  }

	/**
	* for 基本信息增加合作关系
	*/
  renderCorpView() {
    const corpTypeBtnList = this.state.corpList.map(item => {
      const { key, btnText, isChecked } = item;
      const corpTypeBtnChecked = isChecked ? styles.corpTypeBtnChecked : null;
      const corpTypeBtnTextChecked = isChecked ? styles.corpTypeBtnTextChecked : null;
      return (
        <TouchableOpacity key={key} activeOpacity={0.5} style={[styles.corpTypeBtn, corpTypeBtnChecked]} onPress={() => { this._didPressCorpBtn(key); }}>
          <Text style={[styles.corpTypeBtnText, corpTypeBtnTextChecked]}>{btnText}</Text>
        </TouchableOpacity>
      );
    });

    return (
      <Modal animationType={"fade"}
        transparent={true}
        visible={this.state.corpModalVisible}
        onRequestClose={() => { }}>
        <View style={styles.containerModal}>
          <View style={styles.corpTypeView}>
            <View style={styles.corpTypeViewTop}>
              <Text></Text>
              <Text style={[styles.corpTypeViewTopText]}>选择合作关系</Text>
              <Text onPress={this._didPressCorpCellBtn.bind(this)} style={[styles.corpTypeViewTopText, styles.corpTypeViewTopTextClose]}>确定</Text>
            </View>
            <View style={styles.corpTypeViewContent}>
              {corpTypeBtnList}
            </View>
          </View>
        </View>
      </Modal>);
  }

	/**
	 * 点击选择合作关系
	 */
  _didPressCorpBtn(key) {
    const corpList = this.state.corpList.map(item => {
      if (item.key == key) {
        item.isChecked = !item.isChecked;
      }
      return item;
    });
    this.setState({
      corpList
    });
  }

	/**
	 * 点击关闭合作关系选项
	 */
  _didPressCorpCellBtn() {

    let corpKeyArray = [];
    let corpTextArray = [];
    this.state.corpList.forEach(item => {
      if (item.isChecked) {
        let corpType = {
          companyId: item.companyId,
          corpType: item.key,
          id: item.id,
        };
        corpKeyArray.push(corpType);
        corpTextArray.push(item.btnText);
      }
    });

    this.sendData.corpTypeList = corpKeyArray;
    const corpTypeText = corpTextArray.length ? corpTextArray.join(',') : '请选择';

    this.setState({
      corpTypeText: corpTypeText,
      corpModalVisible: false,
    });
  }

}

const styles = StyleSheet.create({
  ocrWrap: {
    width: 375 * scale,
    height: GLOBAL.SCREEN_HEIGHT,
    backgroundColor: 'rgba(0, 0, 0, 0)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  loadedCell: {
    width: 75 * scale,
    height: 75 * scale,
    backgroundColor: 'rgba(0, 0, 0, .5)',
    borderRadius: 7,
    justifyContent: 'center',
    alignItems: 'center',
    // position: 'absolute',
    // left: 140 * scale,
    // top: 150 * scale,
  },
  containerModal: {
    width: 375 * scale,
    height: GLOBAL.SCREEN_HEIGHT,
    backgroundColor: 'rgba(0, 0, 0, .3)',
    justifyContent: 'flex-end'
  },
  corpTypeView: {
    width: GLOBAL.SCREEN_WIDTH,
    // height: 204 * scale,
    backgroundColor: '#fff',
    position: 'absolute',
    left: 0,
    bottom: 0,
  },
  corpTypeBtn: {
    width: 84 * scale,
    height: 40 * scale,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F3F3F3',
    borderRadius: 4,
    marginBottom: 14 * scale,
  },
  corpTypeBtnChecked: {
    backgroundColor: style.color.themeColor,
  },
  corpTypeBtnText: {
    fontSize: 14 * scale,
    color: '#8B8B8B'
  },
  corpTypeBtnTextChecked: {
    color: '#fff'
  },
  corpTypeViewContent: {
    borderTopColor: '#e4e4e4',
    borderTopWidth: 1 / PixelRatio.get(),
    paddingTop: 20 * scale,
    flexDirection: 'row',
    justifyContent: 'space-between',
    flexWrap: 'wrap',
    paddingLeft: 30 * scale,
    paddingRight: 30 * scale,
  },
  corpTypeViewTop: {
    flexDirection: 'row',
    alignSelf: 'center',
    justifyContent: 'space-between',
    height: 50 * scale,
    width: GLOBAL.SCREEN_WIDTH,
    paddingLeft: 30 * scale,
    paddingRight: 30 * scale,
  },
  corpTypeViewTopText: {
    fontSize: 14 * scale,
    color: '#404040',
    paddingTop: 14 * scale,
  },
  corpTypeViewTopTextClose: {
    color: style.color.themeColor,
  },
  scrollView: {
    flex: 1,
    backgroundColor: '#fff',
  },
  container: {
    flex: 1,
    alignItems: 'center',
  },
  wrap: {
    width: 345 * scale,
  },
  closeText: {
    fontSize: 36 * scale,
    color: '#000'
  },
  closeTextCell: {
    position: 'absolute',
    left: 10,
    top: 0,
  },
  inputRowRight: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    flexWrap: 'wrap',
    marginRight: 16 * scale,
  },
  expireDateText: {
    color: style.color.themeColor,
    fontSize: 13 * scale,
    padding: 5 * scale,
    borderWidth: 1 / PixelRatio.get(),
    borderColor: style.color.themeColor,
    borderRadius: 5 * scale
  },
  expireDateView: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    flexWrap: 'wrap',
  }
})